#!/bin/bash

# create the filesystems for the 2 clients and the router
# base filesystem is /virt/base.raw
# copying takes forever, so at the moment we're just going to fake it.
# The filesystems are
#   * /virt/router.raw
#   * /virt/vm1.raw
#   * /virt/vm2.raw
#
# To mount the filesystem run:
# $ mount -o loop,offset=32256 /virt/<filesystem>.raw /mnt
#
# each vm needs an ifcfg-eth0 created for it e.g:


# create the tap
# sudo /usr/sbin/tunctl -u tmauch -t divirt0
sudo /usr/sbin/tunctl -t divirt0
sudo /sbin/ifconfig divirt0 192.168.1.1 netmask 255.255.255.0

# create the switch
# subnet1
sudo /usr/bin/vde_switch -s /tmp/vdesock1 -M /tmp/vdemgmt1 -d -p /tmp/vdepid1
# subnet2
sudo /usr/bin/vde_switch -s /tmp/vdesock2 -M /tmp/vdemgmt2 -d -p /tmp/vdepid2


# start the router
sudo vdeqemu /virt/router.raw \
    -pidfile /tmp/router.pid \
    -monitor unix:/tmp/router-monitor.sock,server,nowait \
    -daemonize \
    -vnc none \
    -m 128M \
    -usbdevice tablet \
    -net nic,macaddr=52:54:00:12:34:56 -net tap,ifname=divirt0,script=/bin/true \
    -net nic,macaddr=52:54:00:12:34:57 -net vde,sock=/tmp/vdesock1 \
    -net nic,macaddr=52:54:00:12:34:58 -net vde,sock=/tmp/vdesock2

# If dhcp is used, the router needs to be up before proceeding.

# start the two clients
sudo vdeqemu /virt/vm1.raw \
    -pidfile /tmp/vm1.pid \
    -monitor unix:/tmp/vm1-monitor.sock,server,nowait \
    -daemonize \
    -vnc none \
    -m 128M \
    -usbdevice tablet \
    -net nic,macaddr=52:54:00:12:34:59 -net vde,sock=/tmp/vdesock1

sudo vdeqemu /virt/vm2.raw \
    -pidfile /tmp/vm2.pid \
    -monitor unix:/tmp/vm2-monitor.sock,server,nowait \
    -daemonize \
    -vnc none \
    -m 128M \
    -usbdevice tablet \
    -net nic,macaddr=52:54:00:12:34:5a -net vde,sock=/tmp/vdesock2

# Notes
#   * vnc displays > 99 seem to have troubles
#   * ip_forward needs to be enabled on the router (/etc/sysctl.conf)
#   * router needs to turn on NAT
#      * iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
#      * service iptables save
